<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>36氪 - 首页</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<link rel="stylesheet" href="css/mui.min.css">
		<link rel="stylesheet" href="css/app.css" />
		<style>
			html,
			body {
				min-height: 100%;
			}
			.kr-article .kr-table-view .mui-media-body {
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 3;
				-webkit-box-orient: vertical;
				white-space: normal!important;
				word-wrap: break-word;
				height: 63px;
			}
			.kr-article .kr-table-view .kr-time {
				position: absolute;
				left: 110px;
				bottom: 8px;
			}
		</style>
	</head>

	<body class="kr-article">
		<div id="pullrefresh" class="mui-content mui-scroll-wrapper">
			<div class="mui-scroll">
				<div id="slider" class="mui-slider kr-slider mui-hidden">
					<div class="mui-slider-group">
						<div class="mui-slider-item">
							<a id="slider-image" href="javascript:;" style="background-image: url(img/blank.jpg);">
								<div id="slider-title" class="mui-slider-title"></div>
								<div class="kr-image-overlay"></div>
							</a>
						</div>
					</div>
				</div>
				<ul id="kr-news" class="mui-table-view kr-table-view">
				</ul>
			</div>
		</div>
		<script id="news-template" type="text/x-handlebars-template">
			<li id="news_{{id}}" class="mui-table-view-cell mui-media">
				<a href="detail.html?guid={{guid}}" data-guid="{{guid}}">
					<div class="mui-media-object mui-pull-left">
						<img src="{{image}}" />
					</div>
					<div class="mui-media-body">
						{{title}}
					</div>
					<p class='kr-time'>{{humanize}}</p>
				</a>
			</li>
		</script>
		<script type="text/javascript" charset="UTF-8" src="js/handlebars-v2.0.0.js"></script>
		<script type="text/javascript" charset="UTF-8" src="js/mui.min.js"></script>
		<script type="text/javascript" charset="UTF-8" src="js/feed.js"></script>
		<script type="text/javascript" charset="UTF-8" src="js/html5sql.js"></script>
		<script type="text/javascript" charset="UTF-8" src="js/app.js"></script>
		<script type="text/javascript" charset="UTF-8" src="js/news.js"></script>
		<script>
			var divEl = document.createElement("div");
			var newsSource = document.getElementById("news-template").innerText;
			var newsTemplate = Handlebars.compile(newsSource);
			var newsEl = document.getElementById("kr-news");
			var sliderEl = document.getElementById("slider");
			//初始化下拉刷新模块
			mui.init({
				pullRefresh: {
					container: '#pullrefresh',
					down: {
						callback: pulldownRefresh
					},
					up: {
						contentrefresh: '正在加载...',
						callback: pullupRefresh
					}
				}
			});
			//点击新闻列表，打开新闻详情
			mui('#pullrefresh').on('tap', 'a', function() {
				open_new_detail(this.getAttribute('data-guid'));
			});
			
			//TODO 为了解决系统分享闪屏问题，临时变成双webview
			var detailMainWebview = null;//详情页面父webview
			var detailWebview = null;//详情页面子webview
			function open_new_detail(id){
				if(!detailMainWebview){
					detailMainWebview = plus.webview.getWebviewById('detail_main');
				}
				if(!detailWebview){
					detailWebview = plus.webview.getWebviewById('detail');
				}
				//触发子窗口变更新闻详情
				mui.fire(detailWebview, 'mui.view.beforeshow', {
					guid: id
				});
				//显示新闻详情页面
				detailMainWebview.show('slide-in-right', 200);
			}
			
			
			mui.plusReady(function() {
				//关闭splash界面
				plus.navigator.closeSplashscreen();
				kr.dbReady(function(isFirst) {
					setTimeout(function() {
						document.body.style.backgroundColor = '#efeff4';
						if (!isFirst) {
							console.log("sssss");
							//获取图片轮播区的新闻
							getSlider(true);
							//加载初始化数据
							mui('#pullrefresh').pullRefresh().pullupLoading();
							setTimeout(function() {
								pulldownRefresh();
							}, 2000);
						} else {
							console.log("dddddddd");
							getFeed();
						}
					}, 500);
				});
			});
			var latestPubDate = Number.MAX_VALUE;
			var hasMore = true;

			function getSlider(isLocal) {
				sliderEl.classList.remove('mui-hidden');
				kr.getSlider(isLocal, function(news) { //等feed完成后再加载slider
					console.log("news 333:"+JSON.stringify(news));
					if (news) {
						if (typeof news === 'string') {
							kr.getNewsByGuid(news, updateSlider);
						} else {
							updateSlider(news);
						}
					}
				});
			};

			function getFeed(isClearCache) {
				console.log('getFeed=>' + isClearCache);
				if (isClearCache === 'true') {
					latestPubDate = Number.MAX_VALUE;
					newsEl.innerHTML = ''; //清空所有
					if (!hasMore) { //当清除缓存之前已上拉加载到底需要重置pullrefresh
						mui('#pullrefresh').pullRefresh().refresh(true);
						hasMore = true;
					}
				}
				mui('#pullrefresh').pullRefresh().pullupLoading(function() {
					kr.getFeed(function(hasNew) {
						getSlider(); //加载slider
						kr.getNews(function(news) {
							if (news && news.length > 0) {
								if (latestPubDate === Number.MAX_VALUE) {
									latestPubDate = news.item(news.length - 1).pubDate;
								}
								for (var i = news.length - 1; i >= 0; i--) {
									divEl.innerHTML = newsTemplate(processNews(news.item(i)));
									newsEl.insertBefore(divEl.firstElementChild, newsEl.firstElementChild);
								}
								mui('#pullrefresh').pullRefresh().endPullupToRefresh();
							}
						});
					}, function() {
						getSlider(); //加载slider
						mui('#pullrefresh').pullRefresh().endPullupToRefresh();
					});
				});
			}

			function pulldownRefresh() {
				console.log('pulldown');
				kr.getFeed(function(hasNew) {
					getSlider();
					console.log('hasNew:::::::' + hasNew);
					if (hasNew) {
						kr.getNews(false, hasNew, function(news) {
							if (news) {
								if (latestPubDate === Number.MAX_VALUE) {
									latestPubDate = news.item(news.length - 1).pubDate;
								}
								for (var i = news.length - 1; i >= 0; i--) {
									divEl.innerHTML = newsTemplate(processNews(news.item(i)));
									newsEl.insertBefore(divEl.firstElementChild, newsEl.firstElementChild);
								}
								mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
							}
						});
					} else {
						setTimeout(function() {
							mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
						}, 800);
					}
				});
			};

			function updateSlider(news) {
				var sliderImageEl = document.getElementById("slider-image");
				var sliderTitleEl = document.getElementById("slider-title");
				
				console.log("updateSlider news:"+JSON.stringify(news));
				
				if (news.image) {
					sliderImageEl.setAttribute('style', 'background-image: url("' + news.image + '");');
				} else {
					if (!news.image && news.cover) {
						if (kr.isDownloadImage()) {
							(function(news) {
								news.id = news.guid.substring(news.guid.lastIndexOf('/') + 1, news.guid.length - 5);
								var cover = news.cover.replace('!heading','!slider');
								addDownloadImage(news.id, cover, function(src) {
									kr.updateNews(news.guid, src); //更新数据库
									sliderImageEl.setAttribute('style', 'background-image: url("' + src + '");');
									console.log('slider downloaded image:::' + src);
								});
							})(news);
						}
					}
				}
				sliderImageEl.addEventListener('tap',function () {
					open_new_detail(news.guid);
				});
//				sliderImageEl.href = 'detail.html?guid=' + encodeURIComponent(news.guid);
//				sliderImageEl.setAttribute('data-guid', encodeURIComponent(news.guid));
				sliderTitleEl.innerText = news.title;
			};

			function pullupRefresh() {
				console.log('pullup');
				kr.getNews(latestPubDate, undefined, function(news) {
					if (news && news.length > 0) {
						latestPubDate = news.item(news.length - 1).pubDate;
						for (var i = 0, len = news.length; i < len; i++) {
							divEl.innerHTML = newsTemplate(processNews(news.item(i)));
							newsEl.appendChild(divEl.firstElementChild);
						}
						mui('#pullrefresh').pullRefresh().endPullupToRefresh();
					} else {
						hasMore = false;
						mui('#pullrefresh').pullRefresh().endPullupToRefresh(true);
					}
				}, function() {
					mui('#pullrefresh').pullRefresh().endPullupToRefresh();
				});
			}
			var downloads = {};

			function addDownloadImage(id, url, callback) {
				if (downloads.hasOwnProperty(id)) { //已存在该download
					var download = downloads[id];
					download.callbacks.push(callback); //增加回调
					if (download.finished) { //该download已完成
						callback(download.filepath); //直接回调
					}
				} else { //新增download
//					console.log('新增download::::' + id + '::::' + url);
					var download = {
						callbacks: [callback],
						finished: false,
						filepath: false
					}
					downloads[id] = download;
					kr.downloadImage(id, url, function(imgUrl) {
						plus.io.resolveLocalFileSystemURL(imgUrl, function(entry) {
							download.finished = true;
							download.filepath = entry.toLocalURL();
							mui.each(download.callbacks, function(index, callback) {
								callback(download.filepath);
							});
						}, function(e) {});
					}).start();
				}
			}

			function processNews(news) {
				var news = mui.extend({}, news); //需要clone出来一个新对象，旧对象无法赋值修改
				news.id = news.guid.substring(news.guid.lastIndexOf('/') + 1, news.guid.length - 5);
				news.humanize = kr.humanize(Date.now() - news.pubDate);
				if (!news.image && news.cover) {
					if (kr.isDownloadImage()) {
						(function(news) {
							addDownloadImage(news.id, news.cover + '!slider', function(src) {
								kr.updateNews(news.guid, src); //更新数据库
								setTimeout(function() {
									document.querySelector("#news_" + news.id + ' img').src = src;
									document.querySelector("#news_" + news.id + ' img').setAttribute('data-loaded', 'true');
								}, 100);
//								console.log('list downloaded image:::' + src);
							});
						})(news);
					}
				}
				if (!news.image) {
					news.image = 'img/blank.jpg';
				}
				return news;
			}
		</script>
	</body>

</html>